package com.my.app.tools.core.service.common;

import net.coobird.thumbnailator.Thumbnails;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

public class ImageService {

    /**
     * 图片转字节
     *
     * @param image
     * @return
     * @author guochaohui
     * @date 2020-04-11 10:36
     */
    public static byte[] imageToBytes(BufferedImage image) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "PNG", outputStream);
        byte[] imageData = outputStream.toByteArray();
        outputStream.close();
        return imageData;
    }

    /**
     * 字节转图片
     *
     * @param imageData
     * @return
     * @author guochaohui
     * @date 2020-04-11 10:36
     */
    public static BufferedImage bytesToImage(byte[] imageData) throws Exception {
        ByteArrayInputStream in = new ByteArrayInputStream(imageData);
        BufferedImage image = ImageIO.read(in);
        in.close();
        return image;
    }

    /**
     * 压缩图片
     *
     * @param image
     * @param scale
     * @param quality
     * @return
     * @author guochaohui
     * @date 2020-04-11 10:20
     */
    public static byte[] compressImage(BufferedImage image, double scale, double quality) throws Exception {
        image = Thumbnails.of(image).scale(scale).outputQuality(quality).asBufferedImage();
        byte[] imageData = imageToBytes(image);
        return imageData;
    }

}
